package com.dzl.util;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description:获取当前地址（包括IP，经纬度等）方法处理
 * @author liuguanjun
 * @time:2021年10月28日 14:14:00
 */
public class LocationUtil {

    /**
     * 获取指定IP对应的经纬度（为空返回当前机器经纬度）
     * @param lon_ 经度
     * @param lat_ 纬度
     * @return
     */
    public static LocationEntity getLocation(String lat_,String lon_) {
        LocationEntity locationEntity = new LocationEntity();
        //百度map ak
        String ak = "bvkz6CIUbZVkU0BN0iOWp82PO5fSV4Lv"; //通过百度地图api获取
        try {
            //URL url = new URL("http://api.map.baidu.com/location/ip?ak=" + ak + "&ip=" + ip + "&coor=bd09ll");
            String mapUrl = "https://api.map.baidu.com/geocoder?location="+lat_+","+lon_+"&output=json&key="+ak;
            URL url = new URL(mapUrl);
            InputStream inputStream = url.openStream();
            InputStreamReader inputReader = new InputStreamReader(inputStream);
            BufferedReader reader = new BufferedReader(inputReader);
            StringBuilder sb = new StringBuilder();
            String str;
            do {
                str = reader.readLine();
                sb.append(str);
            } while (null != str);
            str = sb.toString();
            if (str.isEmpty()) {
                return null;
            }
            str = unicodeToString(str);
            str = str.replace("null","");
            System.out.println(str);
            JSONObject jsonObject = JSONObject.parseObject(str);
            String status = jsonObject.getString("status");
            if(status.equals("OK")){
                JSONObject jsonObjectContent = jsonObject.getJSONObject("result");
                String address = jsonObjectContent.getString("formatted_address");
                JSONObject jsonObjectPoint = jsonObjectContent.getJSONObject("location");
                JSONObject jsonObjectAddressDetail = jsonObjectContent.getJSONObject("addressComponent");
                locationEntity.setProvince(jsonObjectAddressDetail.getString("province"));
                locationEntity.setCity(jsonObjectAddressDetail.getString("city"));
                locationEntity.setDistrict(jsonObjectAddressDetail.getString("district"));
                locationEntity.setStreet(jsonObjectAddressDetail.getString("street"));
                locationEntity.setStreetNumber(jsonObjectAddressDetail.getString("street_number"));
                locationEntity.setAddress(address);
                locationEntity.setLon(jsonObjectPoint.getString("lng"));
                locationEntity.setLat(jsonObjectPoint.getString("lat"));
                return locationEntity;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static double EARTH_RADIUS = 6371.393;

    public static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * unicode 计算两个经纬度之间的距离
     * @param lat1 当前地址纬度
     * @param lng1 当前地址经度
     * @param lat2 目标地址纬度
     * @param lng2 目标地址经度
     * @return
     */
    public static double getDistance(double lat1,double lng1,double lat2, double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2)+Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 1000);
        return s;
    }

    /**
     * 获取外网IP
     * @return
     */
    public static String getV4IP() {
        String ip = "";
        String chinaz = "http://pv.sohu.com/cityjson?ie=utf-8";

        String inputLine = "";
        String read = "";
        try {
            URL url = new URL(chinaz);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            while ((read = in.readLine()) != null) {
                inputLine += read;
            }
            System.out.println(inputLine);

        } catch (Exception e) {
            e.printStackTrace();
        }
        /*Pattern p = Pattern.compile("\\<strong class\\=\"red\">(.*?)\\<\\/strong>");
        Matcher m = p.matcher(inputLine);
        if(m.find()){
            String ipstr = m.group(1);
            System.out.println(ipstr);
        }*/
        ip = inputLine.split("=")[1];
        ip = ip.substring(0,ip.length()-1);
        JSONObject jsonObject = JSONObject.parseObject(ip);
        ip = jsonObject.getString("cip")+"###"+jsonObject.getString("cid");
        return ip;
    }

    /**
     * 获取局域网IP
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }


    public static String unicodeToString(String str) {

        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch + "");
        }
        return str;
    }

    public static void main(String[] args) {
        LocationEntity location = LocationUtil.getLocation("30.460249","114.31158155");
        assert location != null;
        String widu=location.getLat();
        String jndu=location.getLon();
        System.out.println(widu);
        System.out.println(jndu);

        //double d = getDistance(29.490295,106.486654,29.615467,106.581515);
        /*double d = getDistance(35.5876228,127.2524551,30.5055024,114.4033492);
        System.out.println(d);*/

    }

}